package com.boco.pciv.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by CC on 2017/6/10.
 * 主数据库配置
 * 注释掉 @Configuration 生效
 */
//@Configuration
//@MapperScan(value = "com.boco.pciv.mapper.Sys",sqlSessionTemplateRef = "sysSqlSessionTemplate")
public class SysDataSourceConfig {
    @Bean(name = "sysDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource myDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sysSqlSessionFactory")
    @Primary
    public SqlSessionFactory mySqlSessionFactory(@Qualifier("sysDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        bean.setTypeAliasesPackage("com.boco.pciv.entity");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/sqlmaps/sys/*.xml"));

        //设置 jdbctype默认为空 oracle需要
        bean.getObject().getConfiguration().setJdbcTypeForNull(JdbcType.VARCHAR);
        return bean.getObject();
    }

    @Bean(name = "sysTransactionManager")
    @Primary
    public DataSourceTransactionManager myTransactionManager(@Qualifier("sysDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sysSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate mySqlSessionTemplate(@Qualifier("sysSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
